<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>栈-基于数组的栈结构封装</title>
</head>
<body>
  <script>
    /**
      push和pop其实就是进栈和出栈操作，最后进的在栈顶（先进后出）
    */
    function Stack () {
      // 构造函数
      this.items = [];
      // push
      Stack.prototype.push = function (ele) {
        this.items.push(ele);
      }

      // pop（查找栈顶的第一个元素，并删除）
      Stack.prototype.pop = function () {
        this.items.pop();
      }

      // peek（查找栈顶的第一个元素，但不删除）
      Stack.prototype.peek = function () {
        return this.items[this.items.length - 1];
      }

      // 判断是否为空
      Stack.prototype.isEmpty = function () {
        return this.items.length === 0;
      }

      // size（获取栈元素的个数）
      Stack.prototype.size = function () {
        return this.items.length;
      }

      // toString（将栈元素转换为字符串）
      Stack.prototype.toString = function () {
        return this.items.map(ele => ele.toString());
      }
    }

    const stack = new Stack();
    console.log('push', stack.push(6));
    console.log('push', stack.push(7));
    console.log('push', stack.push(8));
    console.log('afterPush', stack);
    console.log('pop', stack.pop());
    console.log('afterPop', stack);
    console.log('peek', stack.peek());
    console.log('peek', stack.isEmpty());
    console.log('peek', stack.size());
    console.log('peek', stack.toString());
  </script>
</body>
</html>